<template>
  <div class="setting-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <h2>个人中心</h2>
    </div>

    <!-- 内容区：标签页切换不同设置项 -->
    <el-card shadow="hover" style="margin-top: 15px;">
      <el-tabs v-model="activeTab" type="card" style="width: 100%">
        <!-- 个人信息标签页 -->
        <el-tab-pane label="个人信息" name="info">
          <div class="info-form-container">
            <el-form
              ref="infoFormRef"
              :model="userInfo"
              label-width="120px"
              class="info-form"
            >
              <el-form-item label="用户名">
                <el-input v-model="userInfo.username" disabled />
              </el-form-item>
              <el-form-item label="角色">
                <el-input v-model="userInfo.role" disabled />
              </el-form-item>
              <el-form-item label="创建时间">
                <el-input v-model="userInfo.create_time" disabled />
              </el-form-item>
              <el-form-item label="最后登录时间">
                <el-input v-model="userInfo.last_login" disabled />
              </el-form-item>
              <el-form-item label="联系邮箱" prop="email">
                <el-input v-model="userInfo.email" placeholder="请输入联系邮箱（选填）" />
              </el-form-item>
              <el-form-item label="个人简介" prop="bio">
                <el-input
                  v-model="userInfo.bio"
                  type="textarea"
                  rows="3"
                  placeholder="请输入个人简介（选填）"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="saveUserInfo">保存修改</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>

        <!-- 修改密码标签页 -->
        <el-tab-pane label="修改密码" name="password">
          <div class="password-form-container">
            <el-form
              ref="passwordFormRef"
              :model="passwordForm"
              :rules="passwordRules"
              label-width="120px"
              class="password-form"
            >
              <el-form-item label="原密码" prop="oldPassword">
                <el-input
                  v-model="passwordForm.oldPassword"
                  type="password"
                  placeholder="请输入原密码"
                  show-password
                />
              </el-form-item>
              <el-form-item label="新密码" prop="newPassword">
                <el-input
                  v-model="passwordForm.newPassword"
                  type="password"
                  placeholder="请输入新密码（至少6位）"
                  show-password
                />
              </el-form-item>
              <el-form-item label="确认新密码" prop="confirmPassword">
                <el-input
                  v-model="passwordForm.confirmPassword"
                  type="password"
                  placeholder="请再次输入新密码"
                  show-password
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="changePassword">确认修改</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>

        <!-- 系统设置标签页 -->
        <el-tab-pane label="系统设置" name="system">
          <div class="system-setting-container">
            <el-form label-width="120px">
              <!-- 主题切换 -->
              <el-form-item label="主题模式">
                <el-radio-group v-model="theme" @change="changeTheme">
                  <el-radio label="light">亮色模式</el-radio>
                  <el-radio label="dark">暗黑模式</el-radio>
                </el-radio-group>
              </el-form-item>

              <!-- 权限查看 -->
              <el-form-item label="我的权限">
                <el-card shadow="hover" class="permission-card">
                  <div v-for="(perm, index) in userPermissions" :key="index" class="permission-item">
                    <el-icon><Check /></el-icon>
                    <span>{{ perm }}</span>
                  </div>
                </el-card>
              </el-form-item>

              <!-- 缓存清理 -->
              <el-form-item>
                <el-button
                  type="warning"
                  @click="clearCache"
                  :loading="clearCacheLoading"
                >
                  <el-icon><Delete /></el-icon> 清理本地缓存
                </el-button>
                <span class="cache-tip">（清理后需重新登录）</span>
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, ElIcon } from 'element-plus'
import { Check, Delete, Moon, Sun } from '@element-plus/icons-vue'
import request from '@/api/request'

// 标签页激活状态
const activeTab = ref('info')

// 用户信息
const userInfo = reactive({
  username: '',
  role: '',
  create_time: '',
  last_login: '',
  email: '',
  bio: ''
})

// 修改密码表单
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const passwordRules = reactive({
  oldPassword: [{ required: true, message: '请输入原密码', trigger: 'blur' }],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
})

// 系统设置
const theme = ref('light') // 主题模式：light/dark
const userPermissions = ref([]) // 用户权限列表
const clearCacheLoading = ref(false)

const router = useRouter()
const infoFormRef = ref(null)
const passwordFormRef = ref(null)

// 页面挂载时加载数据
onMounted(() => {
  getUserInfo()
  getPermissions()
  initTheme() // 初始化主题（从本地存储读取）
})

// 1. 获取用户信息
const getUserInfo = async () => {
  try {
    const res = await request.get('/api/user/info/')
    userInfo.username = res.data.username
    userInfo.role = res.data.role || '普通用户'
    userInfo.create_time = res.data.create_time || '未知'
    userInfo.last_login = res.data.last_login || '未登录'
    userInfo.email = res.data.email || ''
    userInfo.bio = res.data.bio || ''
  } catch (error) {
    ElMessage.error('获取用户信息失败：' + (error.response?.data?.msg || error.message))
  }
}

// 2. 获取用户权限
const getPermissions = async () => {
  try {
    const res = await request.get('/api/user/permissions/')
    userPermissions.value = res.data || ['查看平台数据']
  } catch (error) {
    ElMessage.error('获取权限列表失败')
  }
}

// 3. 保存个人信息
const saveUserInfo = async () => {
  try {
    await request.put('/api/user/info/', {
      email: userInfo.email,
      bio: userInfo.bio
    })
    ElMessage.success('个人信息保存成功')
  } catch (error) {
    ElMessage.error('保存失败：' + (error.response?.data?.msg || error.message))
  }
}

// 4. 修改密码
const changePassword = async () => {
  const valid = await passwordFormRef.value.validate()
  if (!valid) return

  try {
    await request.post('/api/user/change-password/', {
      old_password: passwordForm.oldPassword,
      new_password: passwordForm.newPassword
    })
    ElMessageBox.success('密码修改成功，请重新登录')
    // 清除Token并跳登录页
    localStorage.removeItem('token')
    router.push('/login')
  } catch (error) {
    ElMessage.error('修改失败：' + (error.response?.data?.msg || '原密码错误或新密码不符合要求'))
  }
}

// 5. 初始化主题（从本地存储读取）
const initTheme = () => {
  const savedTheme = localStorage.getItem('app-theme')
  if (savedTheme) {
    theme.value = savedTheme
    document.documentElement.classList.toggle('dark', savedTheme === 'dark')
  }
}

// 6. 切换主题
const changeTheme = (val) => {
  localStorage.setItem('app-theme', val)
  document.documentElement.classList.toggle('dark', val === 'dark')
  ElMessage.success(`已切换到${val === 'dark' ? '暗黑' : '亮色'}模式`)
}

// 7. 清理本地缓存
const clearCache = () => {
  ElMessageBox.confirm(
    '确认清理本地缓存吗？清理后需要重新登录',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    clearCacheLoading.value = true
    try {
      // 清除本地存储
      localStorage.clear()
      // 通知后端登出（可选）
      await request.post('/api/user/logout/').catch(() => {}) // 失败不处理
      ElMessage.success('缓存清理成功，即将跳转登录页')
      // 延迟跳转，确保用户看到提示
      setTimeout(() => {
        router.push('/login')
      }, 1000)
    } catch (error) {
      ElMessage.error('清理失败，请手动清除浏览器缓存')
    } finally {
      clearCacheLoading.value = false
    }
  }).catch(() => {
    ElMessage.info('已取消清理')
  })
}
</script>

<style scoped lang="scss">
.setting-container {
  padding: 20px;
}

.page-header {
  padding: 10px 20px;
  h2 {
    margin: 0;
    font-size: 18px;
    color: #333;
  }
}

// 个人信息表单样式
.info-form-container {
  padding: 20px 0;
  .info-form {
    max-width: 600px;
  }
}

// 密码表单样式
.password-form-container {
  padding: 20px 0;
  .password-form {
    max-width: 500px;
  }
}

// 系统设置样式
.system-setting-container {
  padding: 20px 0;
  .permission-card {
    margin-top: 10px;
    .permission-item {
      display: flex;
      align-items: center;
      margin: 8px 0;
      span {
        margin-left: 8px;
        color: #666;
      }
    }
  }
  .cache-tip {
    margin-left: 10px;
    color: #909399;
    font-size: 14px;
  }
}
</style>